#coding=utf-8
#auth:beck shen
#date:2017-10-18

from __future__ import absolute_import

from pytw.tools import log

import sys
import stackless

from twisted.internet import reactor


class MainLoop(object):

    """
    在reactor中调度tasklet
    """

    @classmethod
    def _schedule(cls):
        if stackless.getruncount() > 1:
            stackless.schedule()

    @classmethod
    def _run(cls):
        r = reactor
        r.startRunning()
        while r._started:
            try:
                while r._started:
                    r.runUntilCurrent()
                    cls._schedule()
                    t2 = r.timeout()
                    t = r.running and t2
                    r.doIteration(t)
                    cls._schedule()
            except:
                log.info("mail loop terminated")
            finally:
                cls._schedule()
        sys.exit(0)

    @classmethod
    def run(cls):
        stackless.tasklet(cls._run)()
        stackless.run()
